package io.github.hadyang.leetcode.offer;

import org.junit.Test;

/** @author haoyang.shi */
public class HasPath {

  @Test
  public void test() {
    System.out.println(hasPath("abcesfcsadee".toCharArray(), 3, 4, "bcced".toCharArray()));
    System.out.println(hasPath("abcesfcsadee".toCharArray(), 3, 4, "abcb".toCharArray()));
  }

  static int[][] steps = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

  public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
    char[][] _matrix = new char[rows][cols];

    int k = 0;
    for (int i = 0; i < _matrix.length; i++) {
      for (int j = 0; j < _matrix[i].length; j++) {
        _matrix[i][j] = matrix[k++];
      }
    }

    int[][] flag = new int[rows][cols];

    for (int i = 0; i < _matrix.length; i++) {
      for (int j = 0; j < _matrix[i].length; j++) {
        if (_matrix[i][j] == str[0]) {
          if (hasPath(_matrix, flag, i, j, str, 0)) {
            return true;
          }
        }
      }
    }

    return false;
  }

  private boolean hasPath(char[][] matrix, int[][] flag, int x, int y, char[] str, int index) {
    if (x < 0 || y < 0) return false;
    if (x >= matrix.length || y >= matrix[0].length) return false;

    if (flag[x][y] == 1) return false;

    boolean subRes = false;
    if (matrix[x][y] == str[index]) {
      if (index == str.length - 1) return true;

      flag[x][y] = 1;

      for (int[] step : steps) {
        subRes |= hasPath(matrix, flag, x + step[0], y + step[1], str, index + 1);
      }

      flag[x][y] = 0;
    }

    return subRes;
  }
}
